import transaction

from repoze.bfg.configuration import Configurator
from repoze.tm import after_end
from repoze.tm import isActive

from models import appmaker
from models import DBSession
from webob.exc import HTTPNotFound
from repoze.bfg.view import AppendSlashNotFoundViewFactory
from repoze.bfg.exceptions import NotFound
from eventlet import wsgi

def handle_teardown(event):
    environ = event.request.environ
    if isActive(environ):
        t = transaction.get()
        after_end.register(DBSession.remove, t)

def notfound_view(context, request):
    return HTTPNotFound('Sorry, Not found :(')
custom_append_slash = AppendSlashNotFoundViewFactory(notfound_view)

def locale_negotiator(request):
    supported_locales = ['uk', 'en', 'ru']
    locale_name = request.cookies.get('locale', None)
    if not locale_name or locale_name not in supported_locales:
        locale_name = request.accept_language.best_match(supported_locales, 'en')
    return locale_name

def app(global_config, **settings):
    zcml_file = settings.get('configure_zcml', 'configure.zcml')

    db_string = settings.get('db_string')
    if db_string is None:
        raise ValueError("No 'db_string' in application configuration.")
    db_echo = settings.get('db_echo', True)

    get_root = appmaker(db_string, db_echo)
    config = Configurator(settings=settings, root_factory=get_root)
    config.begin()
    config.load_zcml(zcml_file)
    config.add_view(custom_append_slash, context=NotFound)
    config.end()
    return config.make_wsgi_app()
